package com.meihua.baoleyi.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.bean.MemberPayBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Response;

import static com.meihua.baoleyi.R.id.tv_phone;
import static com.meihua.baoleyi.R.id.tv_price;

/**
 * 作者：jzm on 2017/11/2.
 * 会员充值
 */

public class MemberPayDialog extends DialogFragment {

    private int currentIndex = 0;
    private TextView open;
    private TextView price;
    private TextView phone;
    private LinearLayout addGuide;

    private List<MemberPayBean.DataBean> dataList = new ArrayList<>();

    //存储添加的TextView
    private List<TextView> guideList = new ArrayList<>();
    private int money = 0; //当前导购对应的金额
    private int levelId; //购买会员等级的id

    public MemberPayDialog() {
        super();
    }

    public static MemberPayDialog getInstance(Context mContext, String json){
        MemberPayDialog mPayDialog = new MemberPayDialog();
        Bundle mBundle = new Bundle();
        mBundle.putString("json", json);
        mPayDialog.setArguments(mBundle);
        return mPayDialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //需要去掉标题
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置dialogd的进出动画
//        getDialog().getWindow().setWindowAnimations(R.style.animate_dialog);
        View view = inflater.inflate(R.layout.dialog_member_pay, container, false);
        initView(view);
        return view;
    }

    /**
     * 初始化数据
     * @param view
     */
    private void initView(View view) {
        open = (TextView) view.findViewById(R.id.tv_open);
        addGuide = (LinearLayout) view.findViewById(R.id.ll_guide);
        price = (TextView) view.findViewById(tv_price);
        phone = (TextView) view.findViewById(tv_phone);
        phone.setText(MyApp.getInstance().getPhone());
        setCheckIndex();
        setLinstener();

        String json = getArguments().getString("json");
        MemberPayBean bean = NetHelper.getBeanForJson(MemberPayBean.class, json);
        //把得到的数据存储到集合
        dataList.clear();
        for(MemberPayBean.DataBean data : bean.getData()) {
            dataList.add(data);
        }
        addGuide();
    }

    /**
     * 设置点击监听
     */
    private void setLinstener() {
        //立即开通
        open.setOnClickListener(new View.OnClickListener() {
            @Override
           public void onClick(View v) {
                isCanUpgrade();
            }
        });
    }

    /**
     * 是否可以升级
     */
    private void isCanUpgrade() {
        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("user_id", MyApp.getInstance().getUser_id());
        treeMap.put("level_id",levelId + "");
        NetHelper.post(APIServer.INTRO_JUDGE, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject json = new JSONObject(s);
                    if (json.get("code").equals("100")) {
                        PayDialog payDialog = PayDialog.getInstance(money, levelId);
                        payDialog.show(getFragmentManager(), "dialog");
                        dismiss();
                    } else {
                    ToastUtil.show(getActivity(), "去升级高的级别吧");
                    }
                } catch (Exception ex) {

                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Window mWindow = getDialog().getWindow();
        //设置背景颜色，只有设置了这个属性，宽度才能全屏MANTC_PARENT
        mWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        WindowManager.LayoutParams mParams = mWindow.getAttributes();
        mParams.gravity = Gravity.BOTTOM;
        mParams.width = getActivity().getResources().getDisplayMetrics().widthPixels;
        mParams.height = (int)(getActivity().getResources().getDisplayMetrics().heightPixels*0.5);
        mWindow.setAttributes(mParams);
        //设置点击外面可以消息
        getDialog().setCanceledOnTouchOutside(true);
    }

    /**
     * 动态添加服务器返回的数据
     */
    private void addGuide() {
        if (dataList.size() < 1) {
            return;
        }
        //先移除所有的view
        addGuide.removeAllViews();
        guideList.clear();
        currentIndex = 0;
        //添加guide
        for (MemberPayBean.DataBean data: dataList) {
            View view = (View) LayoutInflater.from(getContext()).inflate(R.layout.item_member_guide, null);
            final TextView textView = view.findViewById(R.id.tv_guide);
            textView.setText(data.getName());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.leftMargin = 36;
            view.setLayoutParams(layoutParams);
            addGuide.addView(view);
            guideList.add(textView);

            //设置点击监听
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        //记录选中项下标
                        int indexOf = guideList.indexOf((TextView) v);
                        currentIndex = indexOf;
                        price.setText(dataList.get(currentIndex).getMembership()+"元");
                        money = dataList.get(currentIndex).getMembership();
                        levelId = dataList.get(currentIndex).getId();
                        setCheckIndex();
                }
            });

        }
        //默认选中第一项
        setCheckIndex();
        price.setText(dataList.get(0).getMembership()+"元");
        money = dataList.get(0).getMembership();
        levelId = dataList.get(0).getId();
    }

    /**
     * 设置选择项颜色变化
     */
    private void setCheckIndex() {
        for (TextView textView: guideList) {
            int indexOf = guideList.indexOf(textView);
            textView.setSelected(false);
            if (currentIndex == indexOf) {
                textView.setSelected(true);
            }
        }
    }
}
